//
//  GSNetworkManager.m
//  GameSky
//
//  Created by lanou on 16/1/10.
//  Copyright © 2016年 NiRongfei. All rights reserved.
//

#import "GSNetworkManager.h"

@implementation GSNetworkManager

+ (void)requestWithUrlStr:(NSString *)urlStr paraDict:(NSDictionary *)paraDict method:(RequestType)method success:(void (^)(NSURLResponse *response, NSData * data))success failure:(void (^)(NSError *error))failure {
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:20];
    // 判断网络请求方式;
    if (method == POST) {
        [request setHTTPMethod:@"POST"];
        if (paraDict.count) {
            //            NSMutableArray *strArray = [NSMutableArray array];
            //            // 遍历参数字典用'='将Key和Value连接起来组成字符串并保存到临时数组中;
            //            for (NSString *key in paraDict) {
            //                NSString *str = [NSString stringWithFormat:@"%@=%@", key, paraDict[key]];
            //                [strArray addObject:str];
            //            }
            //            // 用'&'把数组中字符串素依次连接起来;
            //            NSString *paraString = [strArray componentsJoinedByString:@"&"];
            //            // 添加POST请求携带的请求数据;
            //            [request setHTTPBody:[paraString dataUsingEncoding:NSUTF8StringEncoding]];
            NSData *data = [NSJSONSerialization dataWithJSONObject:paraDict options:NSJSONWritingPrettyPrinted error:nil];
            [request setHTTPBody:data];
        }
    }
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (data) {
            success(response, data);
        } else {
            failure(connectionError);
        }
    }];
}

@end
